package com.tms.app.tms.ui.taskinfo;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.DPoint;
import com.tms.app.tms.R;
import com.tms.app.tms.adapter.NodeAdapter;
import com.tms.app.tms.app.Constant;
import com.tms.app.tms.bean.Node;
import com.tms.app.tms.bean.TestBean;
import com.tms.app.tms.bean.UserInfo;
import com.tms.app.tms.bean.response.BaseResponse;
import com.tms.app.tms.bean.response.TaskInfoRes;
import com.tms.app.tms.db.TaskInfoDBUtil;
import com.tms.app.tms.ui.FeeInfoAC;
import com.tms.app.tms.ui.MapAc;
import com.tms.app.tms.ui.WaybillListAc;
import com.tms.app.tms.ui.base.presenter.BaseListPresenter;
import com.tms.app.tms.ui.base.ui.BaseListActivity;
import com.tms.app.tms.utils.GeoFenceUtil;
import com.tms.app.tms.utils.SharePreferenceUtil;
import com.tms.app.tms.utils.TimeUtil;
import com.tms.app.tms.widget.CommonDialog;
import com.tms.app.tms.widget.CustomLoadMoreView;
import com.tms.app.tms.widget.MyDialogSelect;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.tms.app.tms.utils.TimeUtil.DEFAULT_DATE_FORMAT2;

/**
 * Created by Administrator on 2017/10/28 0028.
 */

public class TaskInfoActivity extends BaseListActivity implements GeoFenceListener {
    TaskInfoP taskInfoP;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.line_fee)
    RelativeLayout lineFee;
    @BindView(R.id.toolbar_right)
    TextView toolbarRight;
    @BindView(R.id.task_head_text)
    TextView taskHeadText;
    @BindView(R.id.task_head_text2)
    TextView taskHeadText2;
    @BindView(R.id.task_head_text3)
    TextView taskHeadText3;
    @BindView(R.id.task_head_text4)
    TextView taskHeadText4;
    @BindView(R.id.layout_fee_1)
    LinearLayout layoutFee1;
    @BindView(R.id.task_head_text5)
    TextView taskHeadText5;
    @BindView(R.id.task_head_text6)
    TextView taskHeadText6;
    @BindView(R.id.task_head_text7)
    TextView taskHeadText7;
    @BindView(R.id.img_task_status)
    TextView imgTaskStatus;
    @BindView(R.id.button1)
    Button button1;
    @BindView(R.id.button2)
    Button button2;
    private int planIdShowType = -1;
    private int planId;
    private TaskInfoRes taskInfo;
    private String mobile = "";
    private CommonDialog commonDialog;
    private String stationName="";
    private String stationAddress="";
    private String stationContent="";
    private String stationPhone="";
    private double log;
    private double lat;
    private int readStatus=1;
    private GeoFenceClient geoFenceClient;
    BaseListPresenter presenter=new BaseListPresenter();
    UserInfo userInfo;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_task_info);
        ButterKnife.bind(this);
        taskInfoP = new TaskInfoP();
        planId = getIntent().getIntExtra("planId", 0);
        readStatus = getIntent().getIntExtra("readStatus", 1);
        userInfo=SharePreferenceUtil.getObject(this,UserInfo.class);
        initView();
        taskInfoP.setiView(this);
        setToolBarTitle("任务详情", -1, -1);
        if (planId == 0) {
            showMsg("无此运单");
            finish();
        }
        taskInfoP.getData(token, planId);
        showLoadingDialog();
    }
    public void initView() {
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        swipeLayout.setOnRefreshListener(taskInfoP);
        customLoadMoreView = new CustomLoadMoreView();
        adapter = new NodeAdapter();
        adapter.setLoadMoreView(customLoadMoreView);
        adapter.setOnItemChildClickListener(taskInfoP);
        adapter.setOnItemClickListener(taskInfoP);
//        adapter.setOnLoadMoreListener(taskInfoP, recyclerView);
        // GridLayoutManager mgr=new GridLayoutManager(getContext(),3);
        LinearLayoutManager mgr = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(mgr);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        geoFenceClient=GeoFenceUtil.getInstance(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void swichTaskStatus(BaseResponse baseResponse) {//// 拒绝/接收
        if (baseResponse.getCode() == 200) {
            if (baseResponse.getWorkType() == 1) {
                List<Node> list = adapter.getData();
                planIdShowType=1;
                taskInfoP.setPlanIdShowType(planIdShowType);
                for (Node node : list) {
                    node.setPlanIdShowType(1);//////派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成
                }
                for (int i = 0; i < list.size(); i++) {
                    Node node = list.get(i);
                    node.setShowType(2);
                    if (i == 0) {
                        if (node.getStatus()!=2){
                            node.setStatus(2);
//                            if (!presenter.uploadGps(token)){
//                                long time= Long.parseLong(TimeUtil.getTime(new Date(),DEFAULT_DATE_FORMAT2));
//                                presenter.uploadGps(token,userInfo.getId()+"",userInfo.getHeadstockId()+"",
//                                        userInfo.getTrailerId()+"",planId+"",
//                                        node.getGate_longitude(),node.getGate_latitude(),time+"");
//                            }
                        }

                    }
                    if (i == 1&&node.getStatus()==0) {
                            node.setStatus(1);
                    }
                }
                adapter.notifyDataSetChanged();
                findViewById(R.id.button_layout).setVisibility(View.GONE);
                imgTaskStatus.setVisibility(View.VISIBLE);
                imgTaskStatus.getBackground().setLevel(2);
                initGeoFence(list);


            }
            if (baseResponse.getWorkType() == 2) {//1:执行；2:拒绝；3：挂起
                showMsg("拒绝成功");
                TaskInfoDBUtil.deleleTask(0, planId);
                // setResult();
                finish();
            }
            if (baseResponse.getWorkType() == 3) {
                showMsg("挂起成功");
                imgTaskStatus.setVisibility(View.VISIBLE);
                imgTaskStatus.getBackground().setLevel(0);
                taskInfoP.onRefresh();
                TaskInfoDBUtil.saveOrUpadateTask(planId,0);
            }
        } else {
            if (baseResponse.getWorkType() == 1) {
                showMsg(baseResponse.getError());
                finish();
            }
        }


    }


    @Subscribe(threadMode = ThreadMode.MAIN)// 任务详情
    public void bandDataToView(TaskInfoRes taskInfoRes) {
        this.taskInfo = taskInfoRes;
        TaskInfoDBUtil.updateTaskReadType(planId, 1);// 设置阅读状态为已读
        if (readStatus==0){// 如果进来时状态是未读 ， 将通知总数减一
            int onNotification=SharePreferenceUtil.getInt(this,"tzhi",0);
            if (onNotification>1)
                SharePreferenceUtil.setValue(this,"tzhi",onNotification-1);
        }
//        SharePreferenceUtil.setValue(this,"tzhi-BG",0);

        switch (taskInfoRes.getCode()) {
            case 200:
                showData(taskInfoRes);
                break;
            case 10010:
                showMsg(taskInfoRes.getError());//派车单已失效
                finish();
                break;
            case 10011:
                showMsg(taskInfoRes.getError());//派车单已拒绝
                finish();
                break;
            default:
                showMsg(taskInfoRes.getError());
        }

        initGeoFence(taskInfoRes.getData().getStationExecList());

    }


    private void initGeoFence(List<Node> nodeList){
        boolean isExec=false;
        for (Node node : nodeList) {
            String customId=planId+"_"+node.getStationExecId();
            if (node.getStatus()==2){
                List<GeoFence> geoFenceList=geoFenceClient.getAllGeoFence();
                for (GeoFence geoFence : geoFenceList) {
                    if (geoFence.getCustomId().equals(customId));
                    {
                        geoFenceClient.removeGeoFence(geoFence);
                        break;
                    }
                }
                isExec=true;
            }
            if (isExec&&node.getStatus()==1){//当前任务执行中且当前节点 为执行中
                Double lon=Double.parseDouble(node.getGate_longitude());
                Double lat=Double.parseDouble(node.getGate_latitude());
                DPoint  dPoint=new DPoint(lon,lat);
                GeoFenceUtil.addGeoFence(geoFenceClient,dPoint,customId);
            }
        }
    }

    public void showData(TaskInfoRes taskInfoRes) {
        this.taskInfo = taskInfoRes;
        stationName=taskInfoRes.getData().getGate_name();
        stationAddress=taskInfoRes.getData().getGate_address();
        stationContent=taskInfoRes.getData().getGate_contact();
        stationPhone=taskInfoRes.getData().getGate_phone();
        lat=taskInfoRes.getData().getLatitude();
        log=taskInfoRes.getData().getLongitude();

        mobile = taskInfoRes.getData().getDianpatchUserMobile();
        taskHeadText.setText("派车单：" + taskInfoRes.getData().getAllotPlanNo());
        String  planStation=taskInfoRes.getData().getGetPlanStation();
        if(planStation==null)
            planStation=taskInfoRes.getData().getGate_name();
        if (planStation!=null&&planStation.length()>0){
            taskHeadText2.setText(" 拿单点：" +planStation);
        }
        taskHeadText3.setText("备注：" + taskInfoRes.getData().getRemark());
        taskHeadText4.setText("费用：" + taskInfoRes.getData().getFee());
        taskHeadText5.setText(" 申请费用：" + taskInfoRes.getData().getReqestFee());
        taskHeadText6.setText("调度人：" + taskInfoRes.getData().getDispatchUserName());
        if (taskInfoRes.getData().getDispatchUserName()==null)
            taskHeadText6.setText("调度人：");
        taskHeadText7.setText(taskInfoRes.getData().getDianpatchUserMobile());
        if (taskInfoRes.getData().getHasExecTask() == 1) {//是否存在正在执行的任务 0 不存在，1存在
            findViewById(R.id.button_layout).setVisibility(View.GONE);

            switch (taskInfoRes.getData().getPlanStatus()) {////派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成
                case 0:
                    planIdShowType = 10;

                    break;
                case 1:
                    planIdShowType = 11;
                    break;
                case 2:
                    planIdShowType = 12;
                    TaskInfoDBUtil.upadateTaskStatusIf(planId);
                    break;
                case 3:
                    planIdShowType = 13;
                    TaskInfoDBUtil.upadateTaskStatusIf(planId);
                    break;
                case 4:
                    planIdShowType = 14;
            }
            //派车单状态 0 待执行，1执行中，2 司机已完成
        } else {
            planIdShowType = taskInfoRes.getData().getPlanStatus();
            switch (taskInfoRes.getData().getPlanStatus()) {////派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成

                case 0:
                    findViewById(R.id.button_layout).setVisibility(View.VISIBLE);
                    button1.setText("执行");
                    button2.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    break;
                case 2:
                    TaskInfoDBUtil.upadateTaskStatusIf(planId); // 执行完成后更改本地状体 关闭  gps获取数据
                    break;
                case 3:
                    TaskInfoDBUtil.upadateTaskStatusIf(planId);
                    break;
                case 4:
                    findViewById(R.id.button_layout).setVisibility(View.VISIBLE);
                    button1.setText("继续执行");
                    button2.setVisibility(View.GONE);
                    break;
            }
        }
        //派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成4 挂起
//        <item android:drawable="@mipmap/dzhix"/>
//    <item android:drawable="@mipmap/guaqi" android:maxLevel="1"/>
//    <item android:drawable="@mipmap/zhixz" android:maxLevel="2"/>
        switch (taskInfoRes.getData().getPlanStatus()) {
            case 0:
                imgTaskStatus.setVisibility(View.VISIBLE);
                imgTaskStatus.getBackground().setLevel(0);
                break;
            case 1:
                imgTaskStatus.setVisibility(View.VISIBLE);
                imgTaskStatus.getBackground().setLevel(2);
                break;
            case 2:
            case 3:
                imgTaskStatus.setVisibility(View.INVISIBLE);
                break;
            case 4:
                imgTaskStatus.setVisibility(View.VISIBLE);
                imgTaskStatus.getBackground().setLevel(1);
                break;
        }
        ////0,没有在执行任务，2，正在执行的任务，1已有在执行任务当前点击为待完成任务3消息跳入，4 历史跳入
        List<Node> list = adapter.getData();
        for (Node node : list) {
            node.setPlanIdShowType(planIdShowType);
        }
        adapter.notifyDataSetChanged();
        taskInfoP.setPlanIdShowType(planIdShowType);

    }


    @OnClick({R.id.line_lianxiren, R.id.toolbar_right, R.id.layout_fee_1, R.id.layout_fee_2,
            R.id.button1, R.id.button2,R.id.layout_getplanstation})
    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {
            case R.id.layout_getplanstation:
                if (StringUtil.isEmpty(stationName)||StringUtil.isEmpty(stationAddress)
                        ||StringUtil.isEmpty(stationContent)||StringUtil.isEmpty(stationPhone)
                        ||lat<1||log<1)
                    break;
                Intent intent2 = new Intent(this, MapAc.class);
                intent2.putExtra("title", stationName);
                intent2.putExtra("adress", stationAddress);
                intent2.putExtra("content", stationContent+" "+ stationPhone);
                intent2.putExtra("lat", lat+"");
                intent2.putExtra("lon", log+"");
                startActivity(intent2);
                break;
            case R.id.line_lianxiren:
                myDialogSelect = new MyDialogSelect(this, this, "拨打电话", mobile);
                myDialogSelect.show();
                break;
            case R.id.dialog_button_1:
                myDialogSelect.close();
                break;
            case R.id.dialog_button_2:
                myDialogSelect.close();
                callPhone(mobile);
                break;
            case R.id.toolbar_right:
                popuDialog.close();
                popuDialog.showPopu(this, toolbarRight, this, "挂起");
                break;
            case R.id.layout_4:
                popuDialog.close();
                taskInfoP.doRefuseTask(SharePreferenceUtil.getToken(TaskInfoActivity.this), planId, 3); //1:执行；2:拒绝；3：挂起
                break;
            case R.id.layout_fee_1:
                Intent intent = new Intent(this, FeeInfoAC.class);
                intent.putExtra("planId", planId);
                intent.putExtra("showType", 0);// 0,费用详情，1 异常费用详情
                startActivity(intent);
                break;
            case R.id.layout_fee_2:
                if (planIdShowType == 1 || planIdShowType == 2 || planIdShowType == 3 ||
                        planIdShowType == 11 || planIdShowType == 12 || planIdShowType == 13)//派车单状态 0 待执行，1执行中，2 司机已完成3，确认已完成
                {
                    Intent intent3 = new Intent(this, WaybillListAc.class);
                    intent3.putExtra("planId", planId);
                    intent3.putExtra("planIdShowType", planIdShowType);
                    startActivityForResult(intent3, 0x666);
                }
                break;
            case R.id.button1:

                commonDialog = CommonDialog.getInstance(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        taskInfoP.doRefuseTask(SharePreferenceUtil.getToken(TaskInfoActivity.this), planId, 1); //1:执行；2:拒绝；3：挂起
                        commonDialog.close();
                    }
                }, "确定要执行吗");
                commonDialog.show();
                break;
            case R.id.button2:
                //taskInfoP.doRefuseTask(SharePreferenceUtil.getToken(this), planId, 2);
                commonDialog = CommonDialog.getInstance(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        taskInfoP.doRefuseTask(SharePreferenceUtil.getToken(TaskInfoActivity.this), planId, 2); //1:执行；2:拒绝；3：挂起
                        commonDialog.close();
                    }
                }, "确定要拒绝吗");
                commonDialog.show();
                break;

        }
    }


    @Override
    public void refreshComplite(String... msg) {
        super.refreshComplite(msg);
        hideNerError();
        swipeLayout.setRefreshing(false);
        swipeLayout.setEnabled(true);
    }

    @Override
    public void refreshNoData(String... msg) {
        super.refreshNoData(msg);
        swipeLayout.setRefreshing(false);
        swipeLayout.setEnabled(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Constant.fineshNodeTask || requestCode == 0x666) {
            taskInfoP.onRefresh();
            showLoadingDialog();
        }
    }

    @Override
    public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
        SharePreferenceUtil.setValue(this,"GeoFence",list);
    }
}
